package com.huang.exception;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.huang.domain.ResultObject;
import io.netty.util.internal.ObjectUtil;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

//因为Filter在controller之前，所以这里用来特殊处理Filter抛出的异常
@RestController
public class ErrorController extends BasicErrorController {

    public ErrorController() {
        super(new DefaultErrorAttributes(), new ErrorProperties());
    }

    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        getErrorProperties().setIncludeException(true);
        getErrorProperties().setIncludeMessage(ErrorProperties.IncludeAttribute.ALWAYS);
        getErrorProperties().setIncludeStacktrace(ErrorProperties.IncludeAttribute.ALWAYS);
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        HttpStatus status = getStatus(request);
        //错误信息
        Object obj = body.get("message");
        //获取异常信息
        String exception = String.valueOf(body.get("exception"));
        //如果是shiro异常则返回666，否则返回500

        int code = "org.apache.shiro.authc.AuthenticationException".equals(exception) ? 666 : 500;
        return new ResponseEntity(ResultObject.fail(code, ObjectUtils.isNull(obj) ? "系统异常，请重新登录！" : String.valueOf(obj)), HttpStatus.OK);
    }
}